//
//  CalendarViewController.m
//  safeLady
//
//  Created by Justsoso on 2017/7/17.
//  Copyright © 2017年 xmy. All rights reserved.
//

#import "CalendarViewController.h"
#import "CalendarCollectionViewCell.h"
#import "PeriodPopOverView.h"

@interface CalendarViewController ()<UICollectionViewDelegate,UICollectionViewDataSource>

@property (nonatomic, strong) UIView *backgroundView;

/** 日历 */
@property (nonatomic, strong) UILabel *dateLabel;                        //日期文本
@property (nonatomic, strong) UICollectionView *calendarCollectionView;  //集合视图
@property (nonatomic, strong) NSCalendar *calendar;                      //日历
@property (nonatomic, strong) NSMutableArray *dataArray;                 //存储日期和空白的数组
@property (nonatomic, assign) NSInteger dayCount;                        //每个月的天数
@property (nonatomic, assign) NSInteger firstDay;                        //某年某月第一天星期几
@property (nonatomic, assign) NSInteger frontBlankCount;                 //每个月前面空白的个数
@property (nonatomic, assign) NSInteger backBlankCount;                  //每个月后面空白的个数
@property (nonatomic, strong) NSDateComponents *monthDateComponents;     //用于保存目前是几月
@property (nonatomic, strong) NSString *today;

@property (nonatomic, assign) NSInteger nextMonthDays;                   //下月显示的日期

@property (nonatomic, strong) UIView *markView;                          //大姨妈各颜色标注




@end

@implementation CalendarViewController


- (NSMutableArray *)dataArray {
    if (!_dataArray) {
        _dataArray = [[NSMutableArray alloc] init];
    }
    return _dataArray;
}

- (NSCalendar *)calendar {
    if (!_calendar) {
        _calendar = [NSCalendar currentCalendar];
        _calendar.firstWeekday = 2;
        _calendar.minimumDaysInFirstWeek = 1;
    }
    return _calendar;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    /* 获取当前月份 */
    self.monthDateComponents = [self.calendar components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay fromDate:[NSDate date]];
    
    self.title = [NSString stringWithFormat:@"%@年%@月",@(self.monthDateComponents.year), @(self.monthDateComponents.month)];
    
    self.backgroundView = [[UIView alloc] initWithFrame:CGRectMake(0, 74, self.view.width, self.view.height)];
    self.backgroundView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.backgroundView];
    
    self.backgroundView.cornerRadius = 20;
    self.backgroundView.shadowColor = [UIColor lightGrayColor];
    self.backgroundView.shadowOffset = CGSizeMake(0, 2);
    self.backgroundView.shadowRadius = 4;
    self.backgroundView.shadowOpacity = 0.9;
    
    /* 添加日历 */
    [self addCalendar];
    
    /* 添加日历底部标注 */
    [self addmarkView];
    
    /* 刷新日历数据 */
    [self updateCalendarCollectionView];
    
    self.firstDay = [self GetTheWeekOfDayByYera:self.monthDateComponents.year andByMonth:self.monthDateComponents.month];
    
    //在日历上显示的下个月的数字
    self.nextMonthDays = 1 ;
    
    NSString *month = [self changeLength:[NSString stringWithFormat:@"%li",self.monthDateComponents.month]];
    NSString *day = [self changeLength:[NSString stringWithFormat:@"%li",self.monthDateComponents.day]];
    self.today = [NSString stringWithFormat:@"%li%@%@",self.monthDateComponents.year,month,day];
    
    
    /* 添加滑动手势 */
    UISwipeGestureRecognizer *leftSwipe = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeDo:)];
    leftSwipe.direction = UISwipeGestureRecognizerDirectionLeft;
    [self.calendarCollectionView addGestureRecognizer:leftSwipe];
    UISwipeGestureRecognizer *rightSwipe = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeDo:)];
    rightSwipe.direction = UISwipeGestureRecognizerDirectionRight;
    [self.calendarCollectionView addGestureRecognizer:rightSwipe];
    
}


/**
 日期字符串加0
 */
- (NSString *)changeLength:(NSString *)str {
    
    if (str.length == 1) {
        
        str = [@"0" stringByAppendingString:str];
    }
    return str;
}

/**
 手势的事件
 */
- (void)swipeDo:(UISwipeGestureRecognizer *)gesture {
    
    if(gesture.direction == UISwipeGestureRecognizerDirectionLeft) {
        
        [self nextAction];
    }
    if(gesture.direction == UISwipeGestureRecognizerDirectionRight) {
        
        [self beforeAction];
    }
}

/**
 前选按钮的事件
 */
- (void)beforeAction {
    
    /* 刷新日历数据 */
    self.monthDateComponents.month --;
    if (self.monthDateComponents.month == 0) {
        
        self.monthDateComponents.month = 12;
        self.monthDateComponents.year --;
    }
    self.firstDay = [self GetTheWeekOfDayByYera:self.monthDateComponents.year andByMonth:self.monthDateComponents.month];
    self.title = [NSString stringWithFormat:@"%@年%@月",@(self.monthDateComponents.year), @(self.monthDateComponents.month)];
    [self updateCalendarCollectionView];
    self.nextMonthDays = 1;
    
}

/**
 后选按钮的事件
 */
- (void)nextAction {
    
    /* 刷新日历数据 */
    self.monthDateComponents.month ++;
    if (self.monthDateComponents.month == 13) {
        
        self.monthDateComponents.month = 1;
        self.monthDateComponents.year ++;
    }
    self.firstDay = [self GetTheWeekOfDayByYera:self.monthDateComponents.year andByMonth:self.monthDateComponents.month];
    self.title = [NSString stringWithFormat:@"%@年%@月",@(self.monthDateComponents.year), @(self.monthDateComponents.month)];
    [self updateCalendarCollectionView];
    self.nextMonthDays = 1;
    
}



/**
 添加日历
 */
- (void)addCalendar {
    
    CGFloat width = (self.backgroundView.frame.size.width - W(20)) / 7;
    CGFloat height = H(40);
    UICollectionViewFlowLayout *flow = [[UICollectionViewFlowLayout alloc] init];
    flow.itemSize = CGSizeMake(width, height);
    flow.minimumLineSpacing = 0;
    flow.minimumInteritemSpacing = 0;
    
    self.calendarCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, 0, 0) collectionViewLayout:flow];
    self.calendarCollectionView.delegate = self;
    self.calendarCollectionView.dataSource = self;
    self.calendarCollectionView.backgroundColor = [UIColor clearColor];
    [self.backgroundView addSubview:self.calendarCollectionView];
    [self.calendarCollectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.backgroundView.mas_top);
        make.width.equalTo(@(self.backgroundView.frame.size.width - W(20)));
        make.centerX.equalTo(self.backgroundView.mas_centerX);
        make.height.equalTo(@(height * 7));
        
    }];
    
    [self.calendarCollectionView registerClass:[CalendarCollectionViewCell class] forCellWithReuseIdentifier:@"CalendarCell"];
    
}


/**
 日历表底部标注
 */
- (void)addmarkView {
    
    CGFloat allHeight = H(16.f);
    CGFloat viewHeight = H(45);
    CGFloat labelY = (viewHeight - allHeight) / 2;
    
    /* 背景视图 */
    self.markView = [[UIView alloc] init];
    self.markView.backgroundColor = [UIColor colorWithHex:0xFFFFFF];
    [self.backgroundView addSubview:self.markView];
    [self.markView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.calendarCollectionView.mas_bottom);
        make.centerX.equalTo(self.calendarCollectionView.mas_centerX);
        make.width.equalTo(@(self.backgroundView.width));
        make.height.equalTo(@(viewHeight));
    }];
    
    UILabel *topLine = [[UILabel alloc] init];
    topLine.backgroundColor = [UIColor colorWithHex:0xf7f7f7];
    [self.markView addSubview:topLine];
    [topLine mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.markView.mas_top).offset(0.5);
        make.left.equalTo(self.calendarCollectionView.mas_left);
        make.right.equalTo(self.calendarCollectionView.mas_right);
        make.height.equalTo(@1);
    }];
    
    UILabel *bottomLine = [[UILabel alloc] init];
    bottomLine.backgroundColor = [UIColor colorWithHex:0xf7f7f7];
    [self.markView addSubview:bottomLine];
    [bottomLine mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.markView.mas_bottom).offset(0.5);
        make.left.equalTo(self.markView.mas_left);
        make.right.equalTo(self.markView.mas_right);
        make.height.equalTo(@1);
    }];
    
    
    
    for (int i = 0; i < 4; i++) {
        
        NSArray *colors = @[[UIColor colorWithHex:0xB0B1C9],[UIColor colorWithHex:0xDBDBE4],[UIColor colorWithHex:0xBDBBBB],[UIColor colorWithHex:0x6D6C6D]];
        UILabel *round = [[UILabel alloc] initWithFrame:CGRectMake(W(20) + (W(60) + allHeight) * i, labelY, allHeight, allHeight)];
        round.backgroundColor = colors[i];
        round.cornerRadius = allHeight / 2;
        round.masksToBounds = YES;
        [self.markView addSubview:round];
        
        NSArray *titles = @[@"月经期",@"预测经期",@"安全期",@"排卵期"];
        UILabel *title = [[UILabel alloc] init];
        title.text = titles[i];
        title.textColor = [UIColor colorWithHex:0x9A999A];
        title.font = [UIFont systemFontOfSize:12];
        [self.markView addSubview:title];
        [title mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(round.mas_right).offset(W(8));
            make.centerY.equalTo(round.mas_centerY);
            make.height.equalTo(@(allHeight));
        }];
    }
    
    
}

/**
 更新日历信息
 */
- (void)updateCalendarCollectionView {
    
    NSDateComponents *firstDayComponents = [[NSDateComponents alloc] init];
    firstDayComponents.year = self.monthDateComponents.year;
    firstDayComponents.month = self.monthDateComponents.month;
    firstDayComponents.day = 1;
    NSDate *firstDay = [self.calendar dateFromComponents:firstDayComponents];
    
    NSDateComponents *dateComponents = [self.calendar components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitWeekday fromDate:firstDay];
    
    NSRange range = [self.calendar rangeOfUnit:NSCalendarUnitDay inUnit:NSCalendarUnitMonth forDate:firstDay];
    self.dayCount = range.length;
    self.dataArray = nil;
    self.frontBlankCount  = dateComponents.weekday - self.calendar.firstWeekday + 1;
    if (self.frontBlankCount  < 0) {
        
        self.frontBlankCount  += 7;
    }
    for (int i = 0; i < self.frontBlankCount; i++) {
        
        [self.dataArray addObject:@""];
    }
    for (int i = 0; i < range.length; i++) {
        [self.dataArray addObject:[NSString stringWithFormat:@"%@", @(i + 1)]];
        
    }
    NSInteger weeks = 0;
    NSInteger aaa = self.dataArray.count / 7;
    NSInteger bbb = self.dataArray.count % 7;
    if (bbb == 0) {
        weeks = aaa;
    } else {
        weeks = aaa + 1;
    }
    self.backBlankCount = 42 - self.dataArray.count;
    for (int i = 0; i < self.backBlankCount; i++) {
        [self.dataArray addObject:@""];
    }
    [self.calendarCollectionView reloadData];
    self.nextMonthDays = 1;
}


/**
 设置段数
 */
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 2;
}


/**
 设置单元格数量
 */
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    if (section == 0) return 7;
    
    return self.dataArray.count;
}


/**
 设置单元格内容
 */
- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    CalendarCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"CalendarCell" forIndexPath:indexPath];
    
    if (indexPath.section == 0) {
        cell.dateLabel.textColor = [UIColor colorWithHex:0xE3E3EA];
        if (indexPath.row == 0) cell.dateLabel.text = @"日";
        if (indexPath.row == 1) cell.dateLabel.text = @"一";
        if (indexPath.row == 2) cell.dateLabel.text = @"二";
        if (indexPath.row == 3) cell.dateLabel.text = @"三";
        if (indexPath.row == 4) cell.dateLabel.text = @"四";
        if (indexPath.row == 5) cell.dateLabel.text = @"五";
        if (indexPath.row == 6) cell.dateLabel.text = @"六";
    }else if (indexPath.row < self.firstDay){
        
        cell.dateLabel.textColor = [UIColor colorWithHex:0xB8B6B6];
        cell.dateLabel.text = [NSString stringWithFormat:@"%ld",self.dayCount - self.firstDay + indexPath.row + 1];
        [cell.bottomLine setHidden:YES];
        
    }else if (indexPath.row > self.firstDay + self.dayCount - 1) {
        cell.dateLabel.textColor = [UIColor colorWithHex:0xB8B6B6];
        cell.dateLabel.text = [NSString stringWithFormat:@"%ld",self.nextMonthDays];
        self.nextMonthDays++;
        [cell.bottomLine setHidden:YES];
        
    }
    else {
        cell.dateLabel.textColor = [UIColor blackColor];
        cell.dateLabel.text = self.dataArray[indexPath.row];
        NSString *month = [self changeLength:[NSString stringWithFormat:@"%li",self.monthDateComponents.month]];
        NSString *day = [self changeLength:cell.dateLabel.text];
        [cell.bottomLine setHidden:YES];

        if ([self.today isEqualToString:[NSString stringWithFormat:@"%li%@%@",self.monthDateComponents.year,month,day]]) {
            
            
            [cell.bottomLine setHidden:NO];
            cell.isToday = YES;
        }
    }
    
    return cell;
}



/**
 日历点击事件
 */
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    CalendarCollectionViewCell *cell = (CalendarCollectionViewCell *)[collectionView cellForItemAtIndexPath:indexPath];
    
    /* 每行的下标 */
    int subscript = indexPath.row % 7;
    
    int a = indexPath.row % 7;
    NSLog(@"%ld   %i",indexPath.row,a);
    if (indexPath.section == 0) {
        
    }
//    else if (subscript == 0){
//        CGPoint point=CGPointMake(cell.origin.x + W(10) + cell.width / 2, cell.origin.y + 74 + (cell.height - cell.dateLabel.height)/2);
//        PeriodPopOverView *view = [[PeriodPopOverView alloc] initWithOrigin:point Width:cell.width * 5 Height:H(95) Direction:kArrowDirectionDown1];
//        [view popView];
//    }
    else {
    CGPoint point=CGPointMake(cell.origin.x + W(10) + cell.width / 2, cell.origin.y + 74 + (cell.height - cell.dateLabel.height)/2);
    PeriodPopOverView *view = [[PeriodPopOverView alloc] initWithOrigin:point Width:cell.width * 5 Height:H(95) Direction:kArrowDirectionDown2];
    UIToolbar *toolbar = [[UIToolbar alloc] initWithFrame:view.bounds];
    //    toolbar.backgroundColor = [UIColor clearColor];
    toolbar.barStyle = UIBarStyleDefault;
//    [view addSubview:toolbar];
        
        
    
        
    [view popView];
    
    }
}

#pragma mark - 设置日历 ----- 确定当前月的第一天星期几 -> 当前月份的第一周有几天 -
-(NSInteger)GetTheWeekOfDayByYera:(NSInteger )year andByMonth:(NSInteger )month{
    NSInteger sum = 0;
    for(NSInteger i = 1;i<month;i++){
        sum+=[self getDays:year and:i];
    }
    NSInteger nedDay = sum+1;
    
    return ((year-1)+(year-1)/4 -(year/100)+(year/400)+nedDay)%7;
}
-(NSInteger)getDays:(NSInteger )year and:(NSInteger)day{
    
    NSInteger times [] = {31,28,31,30,31,30,31,31,30,31,30,31};
    
    if ((year%4==0&&year%100!=0)||year%400==0) {
        
        times[1] = 29;
    }
    return (times[day-1]);
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
